package com.foreveross.crawl.adapter;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.foreveross.crawl.common.application.IProxyChannelRelateApplication;
import com.foreveross.crawl.common.application.ITaskModelEntityApplication;
import com.foreveross.crawl.common.cfg.PropertyUtils;
import com.foreveross.crawl.common.cfg.system.EnginePropertiesLoader;
import com.foreveross.crawl.common.exception.TaskStateException;
import com.foreveross.crawl.common.util.RandomBrowserVersion;
import com.foreveross.crawl.common.util.SpringHelper;
import com.foreveross.crawl.enums.RouteTypeEnum;
import com.foreveross.proxyip.IProxyIpProvider;
import com.foreveross.proxyip.ProxyIpModel;
import com.foreveross.proxyip.ProxyIpProviderFactory;
import com.foreveross.proxyip.ProxyipProperties;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.foreveross.taskservice.common.model.TaskAction;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ProxyConfig;
import com.gargoylesoftware.htmlunit.WebClient;
import com.google.common.collect.Lists;

/**
 * 适配器的抽象类 职责：抽象公共方法
 * 
 * @author Deng
 * 
 */
@SuppressWarnings("deprecation")
public abstract class AbstractAdapter extends AbstractAviationAdapter {

	private final static String SPLIT_SYMBOL = "======WEBCRAWL=======SPLIT=======";
	protected Log logger = LogFactory.getLog(getClass());
	protected ProxyIpModel proxyIp;
	protected TaskModel taskQueue;
	protected StringBuffer sourceWebPageContents = null;
	protected IProxyIpProvider ipProvider = null;// 全局的IP参数
	private RouteTypeEnum routeTypeEnum;// 航线任务类型枚举

	protected Long fetch_pre_time = 0L; // 上次执行抓取的时间MS。
	protected Long fetch_interval = 1000L; // 抓取的间隔时间MS，默认1S。

	protected HttpClient globalHttpClient;// 全局的httpClient
	protected WebClient globalWebClient;// 全局的WebClient
	
	protected org.apache.commons.httpclient.HttpClient httpClient;
	
	protected ITaskModelEntityApplication iTaskModelEntityApplication;
	protected IProxyChannelRelateApplication iProxyChannelRelateApplication;
	
	public AbstractAdapter(TaskModel taskQueue) {
		this.taskQueue = taskQueue;
		// 配置上允许使用代理
		if (this.isUseProxyip()){
			ipProvider = ProxyIpProviderFactory.getDefaultProxyProvider();
		}
		/**
		 * 返回这个任务的枚举类型 之所以有这个是因为现在航线多变，有国内单程、国内往返、国际单程、国际往返， 以后可能会有更多，而几乎每个类型的页面解析网址都不一样，所以在执行抓取之前先明确是属于哪种类型，然后执行对应的抓取代码 节省时间！节省解析时间
		 */
		if (taskQueue.getIsInternational() == 0 && taskQueue.getIsReturn() == 0) {
			this.routeTypeEnum = RouteTypeEnum.DOMESTIC_ONEWAYTRIP;
		} else if (taskQueue.getIsInternational() == 0 && taskQueue.getIsReturn() == 1) {
			this.routeTypeEnum = RouteTypeEnum.DOMESTIC_ROUNDTRIP;
		} else if (taskQueue.getIsInternational() == 1 && taskQueue.getIsReturn() == 0) {
			this.routeTypeEnum = RouteTypeEnum.INTERNATIONAL_ONEWAY;
		} else if (taskQueue.getIsInternational() == 1 && taskQueue.getIsReturn() == 1) {
			this.routeTypeEnum = RouteTypeEnum.INTERNATIONAL_ROUND;
		} else {
			this.routeTypeEnum = RouteTypeEnum.DOMESTIC_ONEWAYTRIP;
		}
		sourceWebPageContents = new StringBuffer();
		iTaskModelEntityApplication = (ITaskModelEntityApplication)SpringHelper.getBean(ITaskModelEntityApplication.class);
		iProxyChannelRelateApplication = (IProxyChannelRelateApplication)SpringHelper.getBean(IProxyChannelRelateApplication.class);
	}

	/**
	 * 获得类型
	 * 
	 * @return
	 */
	public RouteTypeEnum getRouteType() {
		return routeTypeEnum;
	}

	/**
	 * 是否使用代理IP
	 * 
	 * @return
	 */
	public boolean isUseProxyip() {
		return taskQueue.isUseProxyip() && ProxyipProperties.isProxyEnable();
	}

	/**
	 * 获得公共的httpClient对象
	 * 
	 * @return
	 */
	public HttpClient getHttpClient() {
		if (this.globalHttpClient == null) {
			globalHttpClient = new DefaultHttpClient();
			// 配置上允许使用代理
			if (this.isUseProxyip()) {
				proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				HttpHost proxyHost = new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http");
				globalHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
			}
			// 模拟浏览器，解决一些服务器程序只允许浏览器访问的问题
			globalHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, RandomBrowserVersion.getBV().getUserAgent());
			globalHttpClient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
			globalHttpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 180000);
			globalHttpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);
		}
		return globalHttpClient;
	}
	
	/**
	 * apache下commons包下的httpclient
	*/

	public org.apache.commons.httpclient.HttpClient getComHttpCient(){
		if(this.httpClient == null){
			httpClient=new org.apache.commons.httpclient.HttpClient();  
			if (this.isUseProxyip()) {
				proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				HttpHost proxyHost = new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http");
				httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
			}
			httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
			httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, RandomBrowserVersion.getBV().getUserAgent());
			httpClient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
			httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 180000);
			httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);
			
		}
		return httpClient;
	}
	
	/**
	 * 获得公共的WebClient对象
	 * 
	 * @return
	 */
	public WebClient getWebClient() {
		if (globalWebClient == null) {
			globalWebClient = new WebClient(RandomBrowserVersion.getBV());
			globalWebClient.getOptions().setJavaScriptEnabled(true);
			globalWebClient.getOptions().setCssEnabled(true);
			globalWebClient.getOptions().setAppletEnabled(true);
			globalWebClient.getOptions().setThrowExceptionOnScriptError(false);
			globalWebClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
			globalWebClient.getOptions().setActiveXNative(false);
			globalWebClient.getOptions().setTimeout(120000);
			globalWebClient.getCookieManager().setCookiesEnabled(true);
			if (this.isUseProxyip()) {
				proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				globalWebClient.getOptions().setProxyConfig(new ProxyConfig(proxyIp.getIp(), proxyIp.getPort()));
			}
		}
		return globalWebClient;
	}
	
	/**
	 * 获取火狐版本下的globalWebClient对象
	 * @return
	 */
	public WebClient getWebClientByFF() {
		if (globalWebClient == null) {
			globalWebClient = new WebClient(BrowserVersion.FIREFOX_24);
			globalWebClient.getOptions().setJavaScriptEnabled(false);
			globalWebClient.getOptions().setCssEnabled(false);
			globalWebClient.getOptions().setAppletEnabled(false);
			globalWebClient.getOptions().setThrowExceptionOnScriptError(false);
			globalWebClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
			globalWebClient.getOptions().setActiveXNative(false);
			globalWebClient.getOptions().setTimeout(120000);
			globalWebClient.getCookieManager().setCookiesEnabled(true);
			if (this.isUseProxyip()) {
				proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				globalWebClient.getOptions().setProxyConfig(new ProxyConfig(proxyIp.getIp(), proxyIp.getPort()));
			}
		}
		return globalWebClient;
	}

	/**
	 * 关闭全局的http或webClient连接对象
	 */
	@Override
	public void destory() {
		if (this.globalWebClient != null) {
			globalWebClient.closeAllWindows();
			globalWebClient = null;
		}
		if (this.globalHttpClient != null) {
			globalHttpClient.getConnectionManager().shutdown();
			globalHttpClient = null;
		}
		if(this.httpClient !=null){
			httpClient.getHttpConnectionManager().closeIdleConnections(0);
			httpClient = null;
		}
		sourceWebPageContents = null;
		proxyIp = null;
	}
	/**
	 * 切换代理IP
	 * @return
	 */
	@Override
	public boolean switchProxyip(){
		if (this.isUseProxyip()) {
			if(proxyIp != null){
				recordProxyIp(false);
			}
			proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
			if (proxyIp != null) {
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				if(globalWebClient != null) globalWebClient.getOptions().setProxyConfig(new ProxyConfig(proxyIp.getIp(), proxyIp.getPort()));
				if(globalHttpClient != null) globalHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http"));
				if(httpClient !=null)httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http"));
			}
		}
		return true;
	}
	/**
	 * 切换WebClient的代理IP
	 */
	public void switchProxyipByWebClient() {
		if (this.isUseProxyip()) {
			if(proxyIp != null){
				recordProxyIp(false);
			}
			proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
			if (proxyIp != null){
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				globalWebClient.getOptions().setProxyConfig(new ProxyConfig(proxyIp.getIp(), proxyIp.getPort()));
			}
		}
	}

	/**
	 * 切换HttpClient的代理IP
	 */
	public void switchProxyipByHttClient() {
		if (this.isUseProxyip()) {
			if(proxyIp != null){
				recordProxyIp(false);
			}
			proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
			if (proxyIp != null) {
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				globalHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http"));
			}
		}
	}

	/**
	 * 切换HttpClient的代理IP
	 */
	public void switchProxyipByComHttClient() {
		if (this.isUseProxyip()) {
			if(proxyIp != null){
				recordProxyIp(false);
			}
			proxyIp = ipProvider.provideProxyIp(taskQueue.getChannel().getId());
			if (proxyIp != null) {
				this.logInfo("使用代理IP："+proxyIp.getProxyIp());
				httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http"));
			}
		}
	}
	
	/**
	 * 设置请求头信息
	 * 
	 * @param request
	 * @param headValue
	 * @throws Exception
	 */
	public void setRequestHead(HttpRequestBase request, Map<String, String> headValue) throws Exception {
		if (request == null || headValue == null || headValue.isEmpty()) {
			return;
		}
		headValue.putAll(createRequestHeads());
		for (Entry<String, String> en : headValue.entrySet()) {
			request.addHeader(en.getKey(), en.getValue());
		}
	}

	public void sort(Double[] data, int low, int high) {
		int i = low;
		int j = high;
		if (low < high) {
			Double pivotKey = data[low];
			while (i < j) {
				while (i < j && data[j].compareTo(pivotKey) > 0) {
					j--;
				}
				if (i < j) {
					data[i] = data[j];
					i++;
				}
				while (i < j && data[i].compareTo(pivotKey) < 0) {
					i++;
				}
				if (i < j) {
					data[j] = data[i];
					j--;
				}
			}
			data[i] = pivotKey;
			sort(data, low, i - 1);
			sort(data, i + 1, high);
		}
	}

	/**
	 * 设置累积流量
	 * 
	 * @param taskQueue
	 * @param lenght
	 */
	public void setLenghtCount(long lenght) {
		long t = taskQueue.getByteLength() + lenght;
		taskQueue.setByteLength(t);
	}

	/**
	 * 适配器每次执行完抓取后不管成功与否，都需要调用此回收方法回收代理IP。<br/>
	 * 
	 * @param status 抓取成功：true， 抓取失败：false
	 */
	protected Boolean rollbackProxyIp(Boolean status) {
		try {
			if (this.isUseProxyip() && proxyIp != null) {
				recordProxyIp(status);//记录代理IP使用情况
				this.proxyIp.setUseStatus(status ? ProxyIpModel.ENBLE : ProxyIpModel.UNENBLE);
				this.ipProvider.rollBackProxyIp(this.proxyIp);
				return true;
			}
		} catch (Exception e) {
			logger.error(String.format("[%s]回收IP出错"));
		}
		return false;
	}

	@Override
	public String getSourceWebPageContents() {
		return sourceWebPageContents.toString();
	}

	/**
	 * 抓取的源网页数据累计存储
	 * 
	 * @param sourceWebPageContents
	 */
	public void appendPageContents(String sourceWebPageContents) {
		//暂时不保存源网页代码。
		//this.sourceWebPageContents.append(sourceWebPageContents).append(SPLIT_SYMBOL);
	}


	/**
	 * 一个用httpGet方式提交数据的方法
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public HttpGet getBaseGet(String url, Map<String, String> params) throws Exception {
		Iterator<Entry<String, String>> i;
		Entry<String, String> en;
		StringBuffer sb = new StringBuffer(url);
		try {
			if(params != null && !params.isEmpty()){
				i = params.entrySet().iterator();
				if (!sb.toString().matches(".*\\?$")) {
					sb.append("?");
				}
				while (i.hasNext()) {
					en = i.next();
					sb.append(java.net.URLEncoder.encode(en.getKey()) + "=" + java.net.URLEncoder.encode(en.getValue()) + "&");
				}
			}
			return new HttpGet(sb.toString().replaceAll("&$", ""));
		} finally {
			en = null;
			i = null;
			sb = null;
		}
	}

	public String getBaseGetUrl(String url, Map<String, String> params) throws Exception {
		Iterator<Entry<String, String>> i;
		Entry<String, String> en;
		StringBuffer sb = new StringBuffer(url);
		try {
			i = params.entrySet().iterator();
			if (!sb.toString().matches(".*\\?$")) {
				sb.append("?");
			}
			while (i.hasNext()) {
				en = i.next();
				sb.append(java.net.URLEncoder.encode(en.getKey()) + "=" + java.net.URLEncoder.encode(en.getValue()) + "&");
			}
			return sb.toString();
		} finally {
			en = null;
			i = null;
			sb = null;
		}

	}

	public URI getUrlOfGetRequest(String requestUrl, Map<String, String> params) throws Exception {
		StringBuilder sb = new StringBuilder(requestUrl);

		if (!requestUrl.matches(".*\\?$")) {
			sb.append("?");
		}

		if (params != null) {
			for (Entry<String, String> entry : params.entrySet()) {
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}

		URL url = new URL(sb.toString());
		URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

		return uri;
	}

	/**
	 * 
	 * 一个用httpPost方式提交数据的方法 帮助传递参数，需要的头文件标识需要自己设置
	 * 
	 */
	public HttpPost getBasePost(String url, Map<String, String> params) throws Exception {
		Iterator<Entry<String, String>> i;
		Entry<String, String> en;
		HttpPost p = new HttpPost(url);
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		UrlEncodedFormEntity reqEntity;
		try {
			if (params != null) {
				i = params.entrySet().iterator();
				while (i.hasNext()) {
					en = i.next();
					parameters.add(new BasicNameValuePair(en.getKey(), en.getValue()));
				}
				reqEntity = new UrlEncodedFormEntity(parameters);
				p.setEntity(reqEntity);
			}
			return p;
		} finally {
			en = null;
			i = null;
			reqEntity = null;
			parameters.clear();
			parameters = null;
		}
	}

	public String excuteRequest(HttpRequestBase request) throws Exception {
		return excuteRequest(request, null);
	}

	/**
	 * 執行一定要間隔指定時間。
	 */
	public String excuteRequest(HttpRequestBase request, Long fetch_interval) throws Exception {
		logger.info("正在抓取：" + request.toString());
		if (fetch_interval == null) fetch_interval = this.fetch_interval;
		// 離上次抓取的時間。
		Long current = System.currentTimeMillis() - fetch_pre_time;
		// 如果離上次抓取的時間不夠 指定时间 ，則等待。
		if (current < fetch_interval) Thread.sleep(fetch_interval - current);
		// 首次抓取等待间隔时间。
		if (fetch_pre_time == 0) Thread.sleep(fetch_interval);
		String page = null;
		try {
			page = excuteRequest(getHttpClient(), request, null);
		}finally {
			fetch_pre_time = System.currentTimeMillis(); // 保存这次执行的时间。
		}
		return page;
	}

	public String excuteRequest(HttpClient h, HttpRequestBase request, boolean isReturnString) throws Exception {
		HttpEntity entity = null;
		try {
			entity = h.execute(request).getEntity();
			if (isReturnString) {
				return EntityUtils.toString(entity);
			} else {
				return null;
			}
		} catch (Exception e) {
			if (this.isUseProxyip()) {
				proxyIp.setUseStatus(ProxyIpModel.UNENBLE);
			}
			throw e;
		} finally {
			EntityUtils.consumeQuietly(entity);
			request.releaseConnection();
			entity = null;
			if (this.isUseProxyip()) {
				//记录代理IP是否成功返回数据
				if(proxyIp.getUseStatus() == ProxyIpModel.ENBLE || proxyIp.getUseStatus() == ProxyIpModel.REPEAT_ENBLE){
					recordProxyIp(true);
				} else {
					recordProxyIp(false);
				}
				ipProvider.rollBackProxyIp(proxyIp);
			}
		}
	}

	public String excuteRequest(HttpClient h, HttpRequestBase request, String charset) throws Exception {
		HttpEntity entity = null;
		try {
			entity = h.execute(request).getEntity();
			return EntityUtils.toString(entity, charset);
		} catch (Exception e) {
			if (this.isUseProxyip()) {
				proxyIp.setUseStatus(ProxyIpModel.UNENBLE);
				recordProxyIp(false);
				ipProvider.rollBackProxyIp(proxyIp);
			}
			throw e;
		} finally {
			EntityUtils.consumeQuietly(entity);
			request.abort();
		}
	}

	// ================反续添加的方法=============================
	public enum Reqeust {
		POST, GET;
	}

	/**
	 * httpcleint执行封闭
	 * 
	 * @param url
	 * @param params
	 * @param encoding
	 * @param requestType
	 * @return
	 * @throws Exception
	 */
	public String execute(String url, Map<String, String> params, String encoding, Reqeust requestType) throws Exception {
		HttpResponse response = getHttpResponse(url, params, requestType);
		HttpEntity httpEntity = response.getEntity();
		String content = EntityUtils.toString(httpEntity, encoding);
		setLenghtCount(content.getBytes().length);
		return content;
	}

	/**
	 * httpcleint执行封闭
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public String execute(String url, Map<String, String> params, Reqeust requestType) throws Exception {
		return execute(url, params, HTTP.UTF_8, requestType);
	}

	/**
	 * 必需在try finally中使用closeHttpClient()方法关闭流
	 * 
	 * @param url
	 * @param params
	 * @param requestType
	 * @return
	 * @throws Exception
	 */
	public HttpResponse getHttpResponse(String url, Map<String, String> params, Reqeust requestType) throws Exception {
		HttpClient httpClient = this.getHttpClient();
		HttpRequestBase request = null;
		
		if (requestType == Reqeust.POST) {
			request = getBasePost(url, params);
		} else {
			request = new HttpGet(getUrlOfGetRequest(url, params));
		}

		setRequestHead(request, createRequestHeads());
		long start = System.currentTimeMillis();
		HttpResponse response = httpClient.execute(request);
		long end = System.currentTimeMillis();
		logger.info(String.format("获取网页类容耗时为：[%s] 毫秒", end - start));
		
		return response;
	}

	public HttpResponse getHttpResponse(String url, Reqeust requestType) throws Exception {
		return getHttpResponse(url, null, requestType);
	}

	public Map<String, String> createRequestHeads() {
		Map<String, String> heads = new HashMap<String, String>();
		/*int versionMain = (int) (Math.random() * 10);
		int version = (int) (Math.random() * 10);
		heads.put("User-Agent", "Mozilla/5.0 (Windows NT 5.2; rv:" + versionMain + "." + version + ".1) Gecko/20100101 Firefox/" + versionMain + "." + version + ".1");*/
		// 设置自动闭关
		heads.put("Connection", "close");

		return heads;
	}
	/**
	 * 适配器内一个公共的方法记录日志信息
	 * @param log
	 */
	public void logInfo(String log){
		if(PropertyUtils.getBooleanProperty(EnginePropertiesLoader.ENGINE_TASK_CRAWL_ACTION_LOG, EnginePropertiesLoader.FILE_NAME)){
			taskQueue.addAction(new TaskAction(TaskAction.TASK_FETCH, new Date().getTime(), log));
			
			try {
				this.iTaskModelEntityApplication.recordTracksOfTask(taskQueue.getId(), log);
			} catch (TaskStateException e) {
				logger.error(e);
			}
		}
	}
	
	/**  
	 * @Description: 记录代理IP执行的任务是否成功
	 * @param isSuccess
	 * @author luofangyi
	 * @date 2014-10-17 下午6:14:20 
	 */ 
	public void recordProxyIp(boolean isSuccess){
		try {
			if(this.isUseProxyip() && this.proxyIp != null){
				String ip = proxyIp.getProxyIp();
				Long channelId = this.taskQueue.getChannel().getId();
				String channelName = this.taskQueue.getChannel().getName();
				this.iProxyChannelRelateApplication.saveOrUpdateProxyIp(channelId, channelName, ip, isSuccess);
			} else {
				logger.error("===========未使用代理IP=================" + this.isUseProxyip() + " |||||| " + this.proxyIp);
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**  
	 * @Description: 记录成功执行的代理IP信息
	 * @author luofangyi
	 * @date 2014-10-17 下午6:15:10 
	 */ 
	public void recordProxyIp(){
		this.recordProxyIp(true);
	}
	
	public TaskModel getTaskQueue() {
		return this.taskQueue;
	}
	
	public void printJson(List<?> objs, String filePath) {
		File file = new File(filePath);
		List<String> excList = Lists.newArrayList();
		excList.add("baseEntityRepository");
		excList.add("planeInfoEntity");
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.setExcludes(excList.toArray(new String[] {}));
		JSONArray array = JSONArray.fromObject(objs, config);
		try {
			FileUtils.writeStringToFile(file, array.toString(), "UTF-8");
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		System.out.println(String.format("JSON:%s", array.toString()));
	}
	
	public void write2File(String filePath, String content) {
		File file = new File(filePath);
		try {
			FileUtils.writeStringToFile(file, content, "UTF-8");
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
}
